import { fetchDetailAPI } from "@/apis/detail";
import type { DetailDataType } from "@/apis/detail";
import { NavBar } from "antd-mobile";
import { useEffect, useState } from "react";
import { useNavigate, useSearchParams } from "react-router-dom";

/**
 * 详情页面组件
 *
 * 该组件用于展示特定ID的内容详情，通过URL参数获取ID，调用API获取详情数据并展示
 *
 * @returns 返回详情页面的JSX元素
 */
const Detail = () => {
  // 存储详情数据的状态
  const [detail, setDetail] = useState<DetailDataType | null>(null);

  // 获取URL查询参数
  const [params] = useSearchParams();
  const id = params.get("id");

  // 组件挂载时获取详情数据
  useEffect(() => {
    /**
     * 异步获取详情数据
     *
     * 通过调用fetchDetailAPI接口获取指定ID的详情数据，并更新到组件状态中
     *
     * @throws {Error} 当获取详情数据失败时抛出错误
     */
    const getDetail = async () => {
      try {
        const res = await fetchDetailAPI(id!);
        setDetail(res.data.data);
      } catch (error) {
        throw new Error("fetch detail error");
      }
    };
    getDetail();
  }, [id]);

  // 导航钩子函数
  const navigate = useNavigate();

  /**
   * 返回上一页
   *
   * 调用navigate函数返回到上一个浏览页面
   */
  const back = () => {
    navigate(-1);
  };

  // 数据加载完成前显示加载提示
  if (!detail) {
    return <div>this is loading...</div>;
  }

  return (
    <div>
      <NavBar onBack={back}>{detail?.title}</NavBar>
      <div
        dangerouslySetInnerHTML={{
          __html: detail?.content,
        }}
      ></div>
    </div>
  );
};

export default Detail;
